<template>
  <div class="main" style="height: 824px">
    <div style="margin: 5px">
      <el-input v-model="pno" placeholder="请输入编号" :suffix-icon="Search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-input v-model="pname" placeholder="请输入名称" :suffix-icon="Search" style="width: 200px; margin-left:5px"
        @keyup.enter.native="loadPost">
      </el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="danger" style="margin-left: 5px" @click="resetParam">重置</el-button>
      <el-button type="success" style="margin-left: 5px" @click="add" :disabled="user.roleLevel === 2">新增</el-button>
      <el-button type="info" style="margin-left: 5px" @click="exportCsv">导出为CSV文件</el-button>
    </div>
    <el-table :data="tableData" :header-cell-style="{ background: '#f3f6fd', color: '#555' }" :border="true">
      <el-table-column prop="pno" label="商品编号"/>
      <el-table-column prop="pname" label="商品名称"/>
      <el-table-column prop="punitPrice" label="商品单价"/>
      <el-table-column prop="sellingPrice" label="商品售价"/>
      <el-table-column prop="vno" label="供应商编号"/>
      <el-table-column prop="pdescription" label="商品描述"/>
      <el-table-column prop="premark" label="备注"/>
      <el-table-column prop="" label="操作">
        <template v-slot:default="scope">
          <el-button size="small" type="success" @click="edit(scope.row)" :disabled="user.roleLevel === 2">编辑</el-button>
          <el-popconfirm title="你确定要删除这个吗?" @confirm="del(scope.row.pno)">
            <template #reference>
              <el-button size="small" type="danger" :disabled="user.roleLevel === 2">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[17]" :small="small"
                   :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   style="bottom: 20px; position: fixed; margin-left: 5px; z-index: 2"/>
    <el-dialog class="el-dialog" v-model="centerDialogVisible" :title="title" width="400px" center @close="resetForm">
      <el-form :model="form" label-width="auto" style="width: 80%; margin-left: 40px;" :rules="rules"
               ref="formRef">
        <el-form-item label="商品编号" prop="pno">
          <el-input :disabled="title === '编辑'" v-model="form.pno"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="pname">
          <el-input v-model="form.pname"/>
        </el-form-item>
        <el-form-item label="商品单价" prop="punitPrice">
          <el-input-number :step="0.01" :precision="2" v-model="form.punitPrice" :min="0.00" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="商品售价" prop="sellingPrice">
          <el-input-number :step="0.01" :precision="2" v-model="form.sellingPrice" :min="form.punitPrice/0.85" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="供应商编号" prop="vno">
          <el-input v-model="form.vno"/>
        </el-form-item>
        <el-form-item label="商品简介" prop="pdescription">
          <el-input type="textarea" v-model="form.pdescription"/>
        </el-form-item>
        <el-form-item label="商品备注" prop="pdescription">
          <el-input type="textarea" v-model="form.premark"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="centerDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="resetFormEditAdd">重置</el-button>
          <el-button type="success" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onBeforeMount, ref} from 'vue';
import axios from 'axios';
import {httpUrl} from '../../main.js';
import {Search} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';
import Papa from "papaparse";

const user = ref(JSON.parse(sessionStorage.getItem("CurUser")));
const currentPage = ref(1);
const pageSize = ref(17);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const total = ref(0);
const tableData = ref();
const pno = ref("");
const pname = ref("")
const pnoCompare = ref("");
const sex = ref('');
const centerDialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  pno: "",
  pname: "",
  punitPrice: 0.00,
  sellingPrice: 0.00,
  vno: "",
  pdescription: "",
  premark: ""
});

const resetFormEditAdd = function () {
  if (title.value == "新增") {
    form.value.pno = ""
  }
  form.value.pname = ""
  form.value.punitPrice = 0.00
  form.value.sellingPrice = 0.00
  form.value.vno = ""
  form.value.pdescription = ""
  form.value.premark = ""
}

const resetForm = function () {
  form.value.pno = ""
  form.value.pname = ""
  form.value.punitPrice = 0.00
  form.value.sellingPrice = 0.00
  form.value.vno = ""
  form.value.pdescription = ""
  form.value.premark = ""
  // formRef.value.resetFields()
}
const rules = ref({
  pno: [
    {required: true, message: '请输入编号', trigger: 'blur'},
    {max: 10, message: '编号长度不能大于10字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.pno) {
          if (title.value === "新增") {
            try {
              axios.get(httpUrl + '/product/findByNo?pno=' + form.value.pno).then((res) => res.data).then((res) => {
                console.log(res);
                if (res.code != 200) {
                  callback()
                } else {
                  callback(new Error("编号已存在"))
                }
              });
            } catch (error) {
              console.log(error);
            }
          }
          if (title.value === "编辑") {
            if (pnoCompare.value === form.value.pno) {
              console.log(pno.value)
              callback()
            } else {
              try {
                axios.get(httpUrl + '/product/findByNo?pno=' + form.value.pno).then((res) => res.data).then((res) => {
                  console.log(res);
                  if (res.code != 200) {
                    callback()
                  } else {
                    callback(new Error("账号已存在"))
                  }
                });
              } catch (error) {
                console.log(error);
              }
            }
          }
        }
      }
      , trigger: 'blur'
    }
  ],
  pname: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
    {min: 1, max: 100, message: '名称长度不能小于1个字符,不能大于100字符', trigger: 'blur'},
  ],
  punitPrice: [
    {type: 'number', message: '单价必须是一个数字', trigger: 'blur'},
  ],
  sellingPrice: [
    {type: 'number', message: '售价必须是一个数字', trigger: 'blur'},
  ],
  vno: [
    {required: true, message: '请输入供应商编号', trigger: 'blur'},
    {max: 10, message: '供应商编号长度不能大于10字符', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (form.value.vno) {
          try {
            axios.get(httpUrl + '/vendor/findByNo?vno=' + form.value.vno).then((res) => res.data).then((res) => {
              console.log(res);
              if (res.code == 200) {
                callback()
              } else {
                callback(new Error("供应商不存在"))
              }
            });
          } catch (error) {
            console.log(error);
          }
        }
      }
      , trigger: 'blur'
    }
  ],
  premark: [
    { max: 1000, message: '备注长度不能大于1000字符', trigger: 'blur' }
  ]
});
const title = ref('')
const id = ref()

const handleSizeChange = (val) => {
  console.log(`每页${val}条`);
  currentPage.value = 1;
  pageSize.value = val;
  loadPost();
};

const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;
  loadPost();
};

const resetParam = () => {
  currentPage.value = 1;
  pno.value = '';
  pname.value = '';
  loadPost();
};

const add = () => {
  title.value = "新增"
  centerDialogVisible.value = true;
};

const doSave = function () {
  try {
    axios.post(httpUrl + '/product/save', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '新增成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('新增失败');
        centerDialogVisible.value = false;
      }
    });
  } catch (error) {
    console.log(error);
  }
}

const doMod = function () {
  try {
    axios.post(httpUrl + '/product/update', form.value).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: '编辑成功',
          type: 'success'
        });
        centerDialogVisible.value = false
        loadPost()
      } else {
        ElMessage.error('编辑失败');
        centerDialogVisible.value = false;
      }
    });
    axios.post(httpUrl + '/details/listP', {
      pno: form.value.pno,
    }).then((res) => {
      console.log(res);
      axios.post(httpUrl + '/details/updateBatch', res.data).then((res) => res.data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          ElMessage({
            message: '级联修改成功',
            type: 'success'
          })
        }else {
          ElMessage.error('级联修改失败');
        }
      })
    });
  } catch (error) {
    console.log(error);
  }
}

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('表单验证成功');
      if (title.value === "编辑") {
        doMod()
      } else {
        doSave()
      }
    } else {
      console.log('表单验证失败');
      return false;
    }
    resetForm()
  });
};

const edit = function (row) {
  console.log(row)
  pnoCompare.value = row.pno
  form.value.pno = row.pno
  form.value.pname = row.pname
  form.value.punitPrice = row.punitPrice
  form.value.sellingPrice = row.sellingPrice
  form.value.vno = row.vno
  form.value.pdescription = row.pdescription
  form.value.premark = row.premark
  title.value = "编辑"
  centerDialogVisible.value = true;
}

const del = function (pno) {
  console.log(pno)
  try {
    axios.get(httpUrl + '/details/findByPno?pno=' + pno).then((res) => res.data).then((res) => {
      if (res.code == 200) {
        ElMessage.error("此项在采购明细中有依赖，请删除采购明细中的依赖项后操作")
      }
      else{
        axios.get(httpUrl + '/outsell/findByPno?pno=' + pno).then((res) => res.data).then((res) => {
          if (res.code == 200) {
            ElMessage.error("此项在销售明细中有依赖，请删除销售明细中的依赖项后操作")
          }
          else{
            axios.get(httpUrl + '/product/delete?pno=' + pno).then((res) => res.data).then((res) => {
              console.log(res);
              if (res.code == 200) {
                ElMessage({
                  message: '删除成功',
                  type: 'success'
                });
                loadPost()
              } else {
                ElMessage.error('删除失败');
              }
            });
          }
        })
      }
    })

  } catch (error) {
    console.log(error);
  }
}

const loadGet = async () => {
  try {
    axios.get(httpUrl + '/product/list').then((res) => res.data).then((res) => {
      console.log(res);
      tableData.value = res;
    });
  } catch (error) {
    console.log(error);
  }
};

const loadPost = async () => {
  try {
    axios.post(httpUrl + '/product/listPage', {
      pageSize: pageSize.value,
      pageNum: currentPage.value,
      param: {
        pno: pno.value,
        pname: pname.value
      }
    }).then((res) => res.data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        tableData.value = res.data;
        total.value = res.total;
      } else {
        alert('获取数据失败');
      }
    });
  } catch (error) {
    console.log(error);
  }
};

const exportCsv = () => {
  const header = {
    'pno': '商品编号',
    'pname': '商品名称',
    'punitPrice': '商品单价',
    'sellingPrice': '商品售价',
    'vno': '供应商编号',
    'pdescription': '商品描述',
    'premark': '商品备注'
  };
  export_csv(header, tableData.value);

  function export_csv(header, data) {
    let list = [];
    for (let i in data) {
      let item = data[i];
      let obj = {};
      for (let key in header) {
        let title = header[key];
        let value = item[key];
        obj[title] = value;
      }
      list.push(obj);
    }

    var csv = Papa.unparse(list);
    let content = new Blob(['\uFEFF' + csv]);
    let urlObject = window.URL || window.webkitURL || window;
    let url = urlObject.createObjectURL(content);
    let el = document.createElement("a");
    el.href = url;
    el.download = "商品表.csv";
    el.click();
    urlObject.revokeObjectURL(url);
  }
}
onBeforeMount(async () => {
  await loadPost();
});
</script>

<style scoped>
.el-dialog {
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
